import React from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  FlatList,
  RefreshControl,
  TextInput,
  StatusBar,
  SafeAreaView
} from "react-native";

import { colors } from "../Style/Colors";
import { withNavigation } from "react-navigation";
import { setPTYPEColor, setSMODEColor } from "./SelectTagColor";
import Loading from "./Loading";
import { setFontSize } from "./SetSize";
import UserData from "../Data/UserData";
import Header from "./Header";
import { getPatientList } from "../api/config";
import NoDataFound from "./NoDataFound";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import _ from "lodash";

export class List extends React.Component {
  state = {
    data: [],
    isLoading: false,
    refreshing: false,
    showSearchBar: false,
    searchText: "",
    fullData: []
  };

  componentDidMount = () => {
    const { code } = this.props;
    const { opdList, ipdList, dischargeList } = UserData;
    if (code === "opd") {
      this.setState({
        data: opdList,
        fullData: opdList
      });
    } else if (code === "ipd") {
      this.setState({
        data: ipdList,
        fullData: ipdList
      });
    } else {
      this.setState({
        data: dischargeList,
        fullData: dischargeList
      });
    }
  };

  onRefresh = () => {
    this.setState({ refreshing: true, isLoading: true });
    const { code } = this.props;
    const { data } = UserData;
    getPatientList(code, data.Code).then(data => {
      this.setState({ data, refreshing: false, isLoading: false });
    });
  };

  onSearchBack = () => {
    this.setState({
      showSearchBar: false
    });
  };

  onSearchPress = () => {
    this.setState({
      showSearchBar: true
    });
  };

  onSearch = text => {
    this.setState({
      searchText: text
    });
    const data = _.filter(this.state.fullData, user => {
      return this.contains(user, text);
    });
    this.setState({
      data
    });
  };

  contains = ({ PAT_NAME, LOC }, query) => {
    if (
      PAT_NAME.includes(query.toUpperCase()) ||
      LOC.includes(query.toUpperCase())
    ) {
      return true;
    }
  };

  render() {
    let { data, isLoading, refreshing, showSearchBar, searchText } = this.state;
    const { type, typeMode, code } = this.props;

    if (data) {
      if (type) {
        data = data.filter(e => e.SMODE === typeMode);
      }
    }
    return (
      <View style={{ flex: 1 }}>
        <StatusBar
          barStyle="light-content"
          hidden={false}
          backgroundColor={colors.primaryDarkColor}
        />
        {showSearchBar ? (
          <SafeAreaView style={{ backgroundColor: colors.primaryColor }}>
            <View style={styles.searchContainer}>
              <Icon
                onPress={this.onSearchBack}
                name="arrow-left"
                size={24}
                color={colors.primaryColor}
              />
              <TextInput
                onChangeText={value => this.onSearch(value)}
                value={searchText}
                style={styles.textInput}
                placeholder="Search Patient Name / Location"
                autoFocus={true}
              />
            </View>
          </SafeAreaView>
        ) : (
          <Header
            text={this.props.code.toUpperCase() + " List"}
            isLogoutIcon={true}
            isBack={true}
            searchBar={true}
            onSearchPress={this.onSearchPress}
          />
        )}
        <View style={{ flex: 1 }}>
          {isLoading ? (
            <Loading />
          ) : data.length === 0 ? (
            <NoDataFound />
          ) : (
            <ListItem
              data={data}
              refreshing={refreshing}
              onRefresh={this.onRefresh}
              type={type}
              code={code}
              navigation={this.props.navigation}
            />
          )}
        </View>
      </View>
    );
  }
}

export const ListItem = ({
  data,
  refreshing,
  onRefresh,
  type,
  code,
  navigation
}) => {
  const setImage = gender => {
    if (gender === "M") {
      return require("../assets/MALE.png");
    } else {
      return require("../assets/FEMALE.png");
    }
  };

  const setString = string => {
    if (string === "SHR") {
      return "SHARE WITH";
    } else {
      return "REFER BY";
    }
  };

  return (
    <FlatList
      data={data}
      keyExtractor={(data, index) => index.toString()}
      initialNumToRender={8}
      maxToRenderPerBatch={2}
      refreshControl={
        <RefreshControl
          colors={[colors.primaryColor]}
          refreshing={refreshing}
          onRefresh={onRefresh}
        />
      }
      renderItem={({ item }) => (
        <TouchableOpacity
          activeOpacity={0.8}
          onPress={() => {
            requestAnimationFrame(() => {
              navigation.navigate("PatientProfile", {
                item
              });
            });
          }}
          style={styles.listWrapper}
        >
          <Image style={styles.imgStyle} source={setImage(item.GENDER)} />
          <View style={{ flex: 1 }}>
            <View style={styles.nameSection}>
              <Text style={styles.title}>
                PIN:{" "}
                <Text style={styles.subTitle}>{item.REGNO || item.RegNo}</Text>
              </Text>
              <Text style={styles.title}>
                {item.REFNO ? "VOUCHER" : "ADM NO"} :{" "}
                <Text style={styles.subTitle}>{item.REFNO || item.IPDNO}</Text>
              </Text>
            </View>
            <View style={styles.nameSection}>
              <Text style={styles.title}>
                Name : <Text style={styles.subTitle}>{item.PAT_NAME}</Text>
              </Text>
            </View>
            <View style={styles.nameSection}>
              <Text style={styles.title}>
                AGE: <Text style={styles.subTitle}>{item.AGE} Y</Text>
              </Text>
              <Text style={styles.title}>
                GENDER: <Text style={styles.subTitle}>{item.GENDER}</Text>
              </Text>
              <View style={styles.tagWrapper}>
                <View
                  style={[
                    styles.tag,
                    { backgroundColor: setPTYPEColor(item.PTYPE) }
                  ]}
                >
                  <Text style={styles.tagText}>{item.PTYPE}</Text>
                </View>
              </View>
            </View>
            <View style={styles.nameSection}>
              <Text style={styles.title}>
                LOCATION : <Text style={styles.subTitle}>{item.LOC}</Text>
              </Text>
              <View style={styles.tagWrapper}>
                <View
                  style={[
                    styles.tag,
                    { backgroundColor: setSMODEColor(item.SMODE) }
                  ]}
                >
                  <Text style={styles.tagText}>{item.SMODE.substr(0, 6)}</Text>
                </View>
              </View>
            </View>
            {type && (
              <View style={styles.nameSection}>
                <Text style={styles.title}>
                  {setString(item.SMODE)} :
                  <Text style={styles.subTitle}> {item.OTHDOC}</Text>
                </Text>
              </View>
            )}
            {code === "discharge" && (
              <View style={styles.nameSection}>
                <Text style={styles.title}>
                  DISCHAGRGE DT :
                  <Text style={styles.subTitle}> {item.ToDate}</Text>
                </Text>
              </View>
            )}
          </View>
        </TouchableOpacity>
      )}
    />
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.lightGrey
  },
  imgStyle: {
    width: 50,
    height: 50,
    alignSelf: "center"
  },
  listWrapper: {
    backgroundColor: colors.whiteColor,
    flexDirection: "row",
    padding: 10,
    marginVertical: 2,
    marginHorizontal: 4,
    elevation: 3,
    shadowColor: "#333",
    shadowOffset: { height: 1, width: 1 },
    shadowOpacity: 0.3
  },
  detailsWrapper: {
    padding: 6
  },
  nameSection: {
    flexDirection: "row",
    padding: 4,
    marginHorizontal: 8
  },
  title: {
    color: "#333",
    fontSize: setFontSize("2.1", "1.9"),
    marginHorizontal: 4
  },
  subTitle: {
    fontSize: setFontSize("2", "1.8"),
    color: "grey",
    marginHorizontal: 4
  },
  tagWrapper: {
    flex: 1,
    alignSelf: "flex-end",
    justifyContent: "center",
    alignItems: "flex-end"
  },
  tag: {
    paddingHorizontal: 12,
    paddingVertical: 2,
    borderRadius: 50,
    justifyContent: "center",
    alignItems: "center"
  },
  tagText: {
    color: "#fff",
    fontSize: setFontSize("2", "1.8") //2 //1.8
  },
  searchContainer: {
    padding: 14,
    backgroundColor: colors.whiteColor,
    flexDirection: "row",
    borderBottomWidth: 0.6,
    borderColor: colors.lightGrey
  },
  text: {
    fontSize: 18,
    color: colors.whiteColor,
    fontWeight: "bold",
    flex: 1
  },
  textInput: {
    padding: 0,
    marginHorizontal: 10,
    fontSize: 16,
    flex: 1
  }
});

export default withNavigation(List);
